/**
 * Created by clakeboy on 15/11/2.
 */
var Ball = function(opt) {
    phy.call(this);

    var self = this;

    //设置空间值
    var space = this.space;
    space.iterations = 60;
    space.gravity = v(0, 500);
    space.sleepTimeThreshold = 0.5;
    space.collisionSlop = 0.5;

    this.balls = [];

    this.addBall = function(data) {
        var width = 60;
        var height = 60;
        var radius = data['radius'] || 40;
        var mass = data['mass'] || width * height / 1000;
        var body = space.addBody(new cp.Body(mass, cp.momentForCircle(mass, 0, radius, v(0, 0))));
        body.setPos(this.canvas2point(data.x,data.y));
        var circle = space.addShape(new cp.CircleShape(body, radius, v(0, 0)));
        circle.setElasticity(0.8);
        circle.setFriction(1);
        circle.setCollisionType(BALL_MASK);
        circle.ballinfo = data;
        this.balls.push(circle);
    };

    function init() {
        self.init(opt['canvas'],opt['width'],opt['height']);
        self.addWalls();
        self.addFence();
        var balls = opt['balls'] || [];
        var line = 0,num = 0,offset=40,rad;
        for (var i=0;i<balls.length;i++) {
            rad = balls[i].radius+2;

            balls[i].x = rad + (num * rad * 2);
            balls[i].y = rad + offset + (line * rad * 2);
            self.addBall(balls[i]);
            num ++;
            if ((i+1) % 4 == 0) {
                line++;
                num = 0;
            }
        }
    }

    var bbContainsBB = function(bb, other)
    {
        return (bb.l <= other.l && bb.r >= other.r && bb.b <= other.b && bb.t >= other.t);
    };

    this.getChooseBall = function() {
        var width = 300,height = 180;
        var offset = (this.width - width)/2;
        var bb = new cp.BB(offset,0,width+offset,height);
        var choose = [];
        for (var i =0;i<this.balls.length;i++) {
            if (bbContainsBB(bb,this.balls[i].getBB())) {
                choose.push(this.balls[i].ballinfo);
            }
        }
        return choose;
    };

    init();
};